package edu.bu.cs673.superkids123.children.model.resources;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

/**
 * Class AudioContentFactory
 * 
 * Reads the Audio Formatted data out of an audio file and into
 * a byte array.
 * 
 * @author David Bardwell
 */

public class AudioContentFactory {

	public byte[] createAudioContent(String audioId) {
		byte audioData[] = null;
		try {
			String audioPath = 
				ChildrenResource.rootChildrenResourcePath +
				"audiocontent/" + audioId;
			URL inputFileName = getClass().getResource(audioPath); 
			File inputFile = new File(inputFileName.getFile());
			FileInputStream fis = new FileInputStream(inputFile);
			DataInputStream dis = new DataInputStream(fis);
			BufferedInputStream bis = new BufferedInputStream(dis);
			// get file size
			long size = inputFile.length();
			audioData = new byte[(int) size + 1];

			// read 1 byte at a time
			boolean done = false;
			int byteRead = 0;
			while (!done) {
				byteRead = bis.read(audioData);
				if (byteRead == -1) {
					done = true;
				}
			}
			bis.close();
			dis.close();
			fis.close();
			return audioData;
		} catch (Exception e) {
			// TODO: better error handling
			System.out.println(e);
			return null;
		}
	}
}
